package com.vsu.bookstore.util;

import java.math.BigDecimal;
import java.sql.SQLException;

import com.vaadin.addon.sqlcontainer.SQLContainer;
import com.vaadin.data.Item;
import com.vsu.bookstore.mvc.model.bean.BookStoreItem;

public class DataUtils
{
  public static void addBookStoreItem(final BookStoreItem bean)
  {
    try
    {
      final SQLContainer container = DatabaseHelper.get().getItemContainer();
      final Object id = container.addItem();
      final Item item = container.getItem(id);
      item.getItemProperty("Title").setValue(bean.getTitle());
      item.getItemProperty("Description").setValue(bean.getDescription());
      item.getItemProperty("Image").setValue(bean.getImage());
      item.getItemProperty("Price").setValue(new BigDecimal(bean.getPrice().toString()));
      item.getItemProperty("Group_ID").setValue(bean.getCategoryId());
      container.commit();
    } catch (final UnsupportedOperationException e)
    {
      e.printStackTrace();
    } catch (final SQLException e)
    {
      e.printStackTrace();
    }
  }

  public static BookStoreItem getBeanById(final Object id)
  {
    final Item item = DatabaseHelper.get().getItemContainer().getItem(id);
    return getBeanByItem(item);
  }

  static public BookStoreItem getBeanByItem(final Item item)
  {
    final BookStoreItem result = new BookStoreItem();
    result.setId((Integer)item.getItemProperty("ID").getValue());
    result.setTitle((String)item.getItemProperty("Title").getValue());
    result.setDescription((String)item.getItemProperty("Description").getValue());
    result.setImage((byte[])item.getItemProperty("Image").getValue());
    result.setCategoryId((Integer)item.getItemProperty("Group_ID").getValue());
    result.setPrice(((BigDecimal)item.getItemProperty("Price").getValue()).doubleValue());
    return result;
  }

  public static Object getBookStoreItemRating(final Item item)
  {
    try
    {
      final Double ratingPoints = (Double)item.getItemProperty("RatingPoints").getValue();
      final Integer voted =  (Integer)item.getItemProperty("Voted").getValue();
      if (voted == null ||
          voted == 0d)
        return 0d;
      return ratingPoints / voted;
    }
    catch(final NullPointerException ex)
    {
      return 0.0;
    }
  }
}
